package com.beidouapp.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.validation.ConstraintViolation;

import com.beidouapp.common.contant.SecurityContant;
import com.beidouapp.common.util.PasswordAuthenticatorUtil;
import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;

import com.beidouapp.common.enums.YesNoEnum;
import com.beidouapp.dao.EmployeeAndRoleDao;
import com.beidouapp.dao.EmployeeDao;
import com.beidouapp.dao.UserAndEmployeeDao;
import com.beidouapp.dao.UserDao;
import com.beidouapp.domain.pojo.Employee;
import com.beidouapp.domain.pojo.EmployeeAndRole;
import com.beidouapp.domain.pojo.User;
import com.beidouapp.domain.pojo.UserAndEmployee;
import com.beidouapp.domain.vo.OrgRoleEmployeeVO;
import com.beidouapp.exception.BusinessException;
import com.beidouapp.security.model.SessionUser;
import com.beidouapp.service.EmployeeService;
import com.beidouapp.translator.TranslatorManager;
import com.beidouapp.utils.UIUtils;

@Service
public class EmployeeServiceImpl implements EmployeeService {
    public static final Logger logger = LoggerFactory.getLogger(EmployeeServiceImpl.class);

    @Autowired
    private LocalValidatorFactoryBean validator;

    @Autowired
    private UserDao userDao;

    @Autowired
    private EmployeeDao employeeDao;

    @Autowired
    private UserAndEmployeeDao userAndEmployeeDao;

    @Autowired
    private EmployeeAndRoleDao employeeAndRoleDao;

    @Autowired
    private TranslatorManager translatorManager;


    @Override
    public Employee getEmployeeByUserId(Long userId) {
        return employeeDao.getEmployeeByUserId(userId);
    }

    @Override
    public List<Employee> findEmployeeListByRoleId(Long roleId) {
        List<Employee> list = employeeDao.findEmployeeListByRoleId(roleId);
        return translatorManager.translate(list);
    }

    @Override
    public List<OrgRoleEmployeeVO> findOrgRoleEmployeesByMap(Map<String, Object> params, Integer offset, Integer limit) {
        params.put(SecurityContant.IS_DEL, YesNoEnum.No.getCode());
        List<OrgRoleEmployeeVO> list = employeeDao.findOrgRoleEmployeesByMap(params, offset, limit);
        return translatorManager.translate(list);
    }

    @Override
    public Integer findOrgRoleEmployeesCountByMap(Map<String, Object> params) {
        return employeeDao.findCountOrgRoleEmployees(params);
    }

    @Override
    public void addEmployee(User user, Employee employee, Long orgId, Long roleId) {
        if (user == null) {
            throw new BusinessException("用户信息不能为空!");
        }
        if (employee == null || StringUtils.isEmpty(employee.getCode())) {
            throw new BusinessException("员工信息或员工编码不能为空!");
        }
        Employee emp = new Employee();
        emp.setCode(employee.getCode());
        List<Employee> list = employeeDao.findEntryList(emp);
        if (!CollectionUtils.isEmpty(list)) {
            throw new BusinessException("员工编码信息重复.");
        }

        User tmpUser = userDao.getUserByLoginName(user.getLoginName());
        if (null != tmpUser) {
            logger.warn("新增的员工{}信息中，用户员{}已存在.", new Object[]{employee.getEmpName(), user.getLoginName()});
            throw new BusinessException("新增的员工" + employee.getEmpName() + "信息中，用户" + user.getLoginName() + "已存在.");
        }

        //插入数据校验
        Set<ConstraintViolation<Employee>> constraintViolations = validator.validate(employee);
        StringBuffer sb = new StringBuffer();
        for (ConstraintViolation<Employee> constraintViolation : constraintViolations) {
            sb.append("\n").append(constraintViolation.getMessage());
        }
        if (sb.length() != 0) {
            throw new RuntimeException(sb.toString());
        }
        SessionUser sessionUser = UIUtils.getSessionUser();
        employee.setCreateBy(sessionUser.getUserId());
        employee.setCreateTime(new Date());
        employee.setEnable("1");
        employee.setIsDel(YesNoEnum.No.getCode());
        employee.setOrgId(orgId);
        // 保存员工信息
        employeeDao.insert(employee);

        try {
            String newPassword = user.getPassword();
            if (StringUtils.isBlank(newPassword)) {
                //TODO:默认密码如何定义？
                newPassword = "123456";
            }
            newPassword = PasswordAuthenticatorUtil.encryptPassword(newPassword);

            user.setPassword(newPassword);
        } catch (Exception e) {
            logger.error("Error:PMS-ERR-01010400,创建密文错误。");
            throw new BusinessException("PMS-ERR-01010400", "创建密文错误。");
        }
        user.setCreateBy(sessionUser.getUserId());
        user.setIsDel(YesNoEnum.No.getCode());
        Date d = new Date();
        user.setCreateTime(d);
        DateTime dt = new DateTime();
        //TODO:密码过期时间多少？
        dt = dt.plusMonths(3);
        user.setExpirationTime(dt.toDate());
        // 保存用户信息
        userDao.insert(user);

        // 保存用户和员工关联关系
        UserAndEmployee record = new UserAndEmployee(employee.getId(), user.getId());
        userAndEmployeeDao.addEntry(record);

        // 保存员工和角色关联关系
        EmployeeAndRole userAndRole = new EmployeeAndRole(employee.getId(), roleId);
        employeeAndRoleDao.addEntry(userAndRole);
    }

    @Override
    public void removeEmployeeBatch(List<Long> employeeIdList) {
        if (CollectionUtils.isEmpty(employeeIdList)) {
            logger.warn("批量删除员工信息时，员工id集合为空.");
            return;
        }
        try {
            for (Long empId : employeeIdList) {
                //删除员工和角色的关系
                EmployeeAndRole employeeAndRole = new EmployeeAndRole(empId, null);
                employeeAndRoleDao.removeEntry(employeeAndRole);

                //获得员工和用户的关联关系.
                List<UserAndEmployee> uaeList = userAndEmployeeDao.findEntryList(new UserAndEmployee(empId, null));
                if (!CollectionUtils.isEmpty(uaeList)) {
                    //删除员工和用户的关系
                    userAndEmployeeDao.removeEntry(new UserAndEmployee(empId, null));
                    for (UserAndEmployee uae : uaeList) {
                        //逻辑删除用户
                        userDao.removeEntryByID(uae.getUserId());
                    }
                }

                //逻辑删除员工
                employeeDao.removeEntryByID(empId);
            }
        } catch (Exception e) {
            logger.error("批量删除员工信息失败！", e);
            throw new BusinessException("批量删除员工信息失败！", e);
        }
    }

    @Override
    public OrgRoleEmployeeVO getEmployeeVOById(Long empId) {
        if (empId == null) {
            logger.error("员工ID不能为空!");
            throw new BusinessException("获得员工信息时，ID不能为空!");
        }
        OrgRoleEmployeeVO vo = employeeDao.getEmployeeVOById(empId);
        return vo;
    }

    @Override
    public void modifyEmployee(User user, Employee employee, Long orgId, Long roleId) {
    	if(orgId==null) orgId= -1l;
        SessionUser sessionUser = UIUtils.getSessionUser();
        user.setUpdateTime(new Date());
        user.setUpdateBy(sessionUser.getUserId());
        userDao.modifyEntry(user);

        employee.setUpdateBy(sessionUser.getUserId());
        employee.setUpdateTime(new Date());
        employee.setOrgId(orgId);
        employeeDao.modifyEntry(employee);
        

        //修改员工和角色关联关系
        EmployeeAndRole userAndRole = new EmployeeAndRole(employee.getId(), null);
        employeeAndRoleDao.removeEntry(userAndRole);
        userAndRole.setRoleId(roleId);
        employeeAndRoleDao.addEntry(userAndRole);
    }

    @Override
    public Employee getEmployeeById(Long id) {
        if (id == null) {
            return null;
        }
        return employeeDao.getEmployeeById(id);
    }

    //------------------------------


}
